#!/usr/bin/env python

#David Fong, released under GPLv3
#part of the code is inspired by
#Jon Berg , turtlemeat.com
# woof -- an ad-hoc single file webserver
# http://www.home.unix-ag.org/simon/woof

import string,cgi,sys,commands
from os import curdir,sep,environ,uname
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        try:
            htmlfile='''<HTML><BODY>
<form method="POST" enctype="multipart/form-data" action="" onSubmit="document.forms[0].childNodes[2].value=document.forms[0].childNodes[1].value; return true">
File to upload: 
<input type=file name=upfile><input type="hidden" id="filename" name="filename" value="" /><br><br>
<input type=submit value=Upload></form></BODY></HTML>
            '''
            self.send_response(200)
            self.send_header('Content-type',    'text/html')
            self.end_headers()
            self.wfile.write(htmlfile)
            return
        except:
            pass

    def do_POST(self):
        global rootnode
        #try:
        ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
        if ctype == 'multipart/form-data':
            query=cgi.parse_multipart(self.rfile, pdict)
        self.send_response(301)
        self.end_headers()
        upfilecontent = query.get('upfile')
        filename=query.get('filename')
        print "Received file:" + filename[0]
        f=open(filename[0],'w')
        f.write(upfilecontent[0])
        f.close()
        self.wfile.write("<html>"+ filename[0]+""" upload done.
        <br> <a href="">Upload another file</a>
        </html>""")

        #except :
        #    pass

def find_ip ():
   if sys.platform == "cygwin":
      ipcfg = os.popen("ipconfig").readlines()
      for l in ipcfg:
         try:
            candidat = l.split(":")[1].strip()
            if candidat[0].isdigit():
               break
         except:
            pass
      return candidat

   environ["PATH"] = "/sbin:/usr/sbin:/usr/local/sbin:" + environ["PATH"]
   platform = uname()[0];

   if platform == "Linux":
      netstat = commands.getoutput ("LC_MESSAGES=C netstat -rn")
      defiface = [i.split ()[-1] for i in netstat.split ('\n')
                                    if i.split ()[0] == "0.0.0.0"]
   elif platform in ("Darwin", "FreeBSD"):
      netstat = commands.getoutput ("LC_MESSAGES=C netstat -rn")
      defiface = [i.split ()[-1] for i in netstat.split ('\n')
                                    if len(i) > 2 and i.split ()[0] == "default"]
   elif platform == "SunOS":
      netstat = commands.getoutput ("LC_MESSAGES=C netstat -arn")
      defiface = [i.split ()[-1] for i in netstat.split ('\n')
                                    if len(i) > 2 and i.split ()[0] == "0.0.0.0"]
   else:
      print >>sys.stderr, "Unsupported platform; please add support for your platform in find_ip().";
      return None

   if not defiface:
      return None

   if platform == "Linux":
      ifcfg = commands.getoutput ("LC_MESSAGES=C ifconfig "
                                  + defiface[0]).split ("inet addr:")
   elif platform in ("Darwin", "FreeBSD", "SunOS"):
      ifcfg = commands.getoutput ("LC_MESSAGES=C ifconfig "
                                  + defiface[0]).split ("inet ")

   if len (ifcfg) != 2:
      return None
   ip_addr = ifcfg[1].split ()[0]

   # sanity check
   try:
      ints = [ i for i in ip_addr.split (".") if 0 <= int(i) <= 255]
      if len (ints) != 4:
         return None
   except ValueError:
      return None

   return ip_addr

def main():
    try:
        portnumber=8080
        server = HTTPServer(('', portnumber), MyHandler)
        print 'started httpserver at...'
        print 'http://' + find_ip() + ':' +str(portnumber)
        server.serve_forever()
    except KeyboardInterrupt:
        print '^C received, shutting down server'
        server.socket.close()

if __name__ == '__main__':
    main()

